<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { createJobDataApi, deleteJobDataApi, updateJobDataApi, getJobDataApi } from "@/api/job"
import { type IGetJobData } from "@/api/job/types/job"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { Plus } from "@element-plus/icons-vue"
import { uploadJobImageList } from "@/api/job"
defineOptions({
  name: "JobList"
})

const loading = ref(true)
const { paginationData } = usePagination()
const imageUrl = ref("")
const fileList = ref<any>([]) /**图片列表 */

//#region 增
const dialogVisible = ref<boolean>(false)
const dialogVisible1 = ref<boolean>(false)
const dialogImageUrl = ref("")
const formRef = ref<FormInstance | null>(null)
const formData = reactive({
  name: "",
  image: ""
})
const formRules: FormRules = reactive({
  name: [{ required: true, trigger: "blur", message: "请输入职位名称" }]
})
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      uploadFuc()
    } else {
      return false
    }
  })
}
const resetForm = () => {
  currentUpdateId.value = undefined
  clearValidate()
  formData.name = ""
  formData.image = ""
  imageUrl.value = ""
  fileList.value = []
}
//#endregion

//#region 删
const handleDelete = (row: IGetJobData) => {
  ElMessageBox.confirm(`正在删除职位：${row.name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteJobDataApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const currentUpdateId = ref<undefined | string>(undefined)
// const currentUpdateName = ref<undefined | string>(undefined)

const handleUpdate = (row: IGetJobData) => {
  currentUpdateId.value = row.id
  // currentUpdateName.value = row.name
  formData.name = row.name
  formData.image = row.image?.split("/image/")[1]
  imageUrl.value = row.image
  fileList.value = row.image?.split(",").map((item: any) => {
    return {
      url: item
    }
  })
  dialogVisible.value = true
}
//#endregion

//#region 查
const tableData = ref<IGetJobData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  name: ""
})
const getTableData = () => {
  getJobDataApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    name: searchData.name || ""
    // phone: searchData.phone || undefined
  })
    .then((res: any) => {
      // paginationData.total = res.data.total
      tableData.value = res.data
      loading.value = false
    })
    .catch(() => {
      tableData.value = []
    })
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const handleRefresh = () => {
  getTableData()
}
//#endregion

// #region  查看薪资标准大图
const handleOpenImgInfo = (imgUrl: any) => {
  dialogVisible1.value = true
  dialogImageUrl.value = imgUrl
}
const restImg = () => {
  dialogVisible1.value = false
  dialogImageUrl.value = ""
}
// #endregion

// #region 确定上传 图片改变
const handleChageImg = (file: any, resfileList: any) => {
  const size = ref(2)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileList.value = []
  } else {
    fileList.value = resfileList
  }
}
// #endregion

// #region 移除图片
const handleRemove = (file: any) => {
  const list = fileList.value
  for (const i in list) {
    if (list[i].uid === file.uid) {
      list.splice(i, 1)
    }
  }
  fileList.value = list
}
const uploadFuc = async () => {
  if (fileList.value.length === 0) {
    ElMessage.error("请上传薪资图")
    return
  }
  const fileData = new FormData()
  fileList.value.forEach((file: any) => {
    fileData.append("file", file.raw)
  })
  if (fileList.value[0].status === "ready") {
    await uploadJobImageList(fileData).then((res: any) => {
      if (res.code == 200) {
        formData.image = res.data.split("/image/")[1]
        fileList.value = []
      }
    })
  }
  if (currentUpdateId.value === undefined) {
    createJobDataApi({
      name: formData.name,
      image: formData.image
    }).then(() => {
      ElMessage.success("新增成功")
      dialogVisible.value = false
      getTableData()
    })
  } else {
    updateJobDataApi({
      id: currentUpdateId.value,
      name: formData.name,
      image: formData.image
    }).then(() => {
      ElMessage.success("修改成功")
      dialogVisible.value = false
      getTableData()
    })
  }
}
// #endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
// ** 清除规则报错信息
const clearValidate = () => {
  formRef.value?.clearValidate()
}
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="职位名">
          <el-input v-model.trim="searchData.name" placeholder="请输入职位名" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">添加职位</el-button>
          <!-- <el-button type="danger" :icon="Delete">批量删除</el-button> -->
        </div>
        <div>
          <!-- <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip> -->
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>

      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="name" label="职位名" align="center" />
          <el-table-column prop="image" label="薪资标准" align="center">
            <template #default="scope">
              <img
                :src="scope.row.image"
                alt=""
                style="cursor: pointer"
                v-if="scope.row.image"
                width="80"
                height="80"
                @click="handleOpenImgInfo(scope.row.image)"
              />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增职位' : '修改职位'"
      @close="resetForm"
      width="60%"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="name" label="职位名">
          <el-input v-model="formData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="image" label="薪资标准">
          <!-- <el-input v-model="formData.image" placeholder="请输入" />
           -->
          <el-upload
            :auto-upload="false"
            :file-list="fileList"
            :show-file-list="true"
            list-type="picture-card"
            :limit="1"
            accept="image/*"
            :on-change="handleChageImg"
            :disabled="fileList.length != 0"
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible1" @close="restImg">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.block {
  padding: 30px 0;
  text-align: center;
  box-sizing: border-box;
  vertical-align: top;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
